//
//  SDStorePhotoViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/7/2.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDStorePhotoViewController.h"
#import "SDPhotoInfoViewController.h"
#import "SDNavigationController.h"
#import "SDTabBarController.h"
#import "SDNavigationBar.h"
#import "SDPaientInfoMgr.h"
#import "SDPaientInfoItem.h"
#import "SDPhotoInfo.h"
#import "SelectViewAlert.h"
#import "SDSelectPaientViewcontroller.h"
#import "SDPaientEditorViewController.h"

@interface SDStorePhotoViewController() <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, SelectViewAlertDelegate>

@property (nonatomic, strong) UICollectionView      *photoCollection;
@property (nonatomic, assign) float                 photoViewWidth;
@property (nonatomic, strong) UIImageView           *photoImageView;

@end

@implementation SDStorePhotoViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self mutStorePhoto]) {
        [self initMutView];
    } else {
        [self initViews];
    }
}

- (BOOL)mutStorePhoto
{
    return !([SDPhotoArray shareInstanse].photoInfoArray.count == 1);
}

- (void)initMutView
{
    BOOL naviHidden = [self navigationBarHidden];
    if (!naviHidden && self.navBar != nil)
    {
        [self.navBar setTitle:@"crash.................."];
        UIImage* addImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_back.png");
        [self.navBar customNaviLeftButton:self action:@selector(onBack:) image:addImg];
        [self.navBar customNaviRightButton:self action:@selector(complete:) title:@"完成"];
    }
    _photoViewWidth = ((kScreenWidth + 1) - 4) / 4;
    
    //创建一个layout布局类
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置布局方向为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _photoCollection = [[UICollectionView alloc] initWithFrame:autoRectTableViewHaveBar(!naviHidden) collectionViewLayout:layout];
    _photoCollection.delegate = self;
    _photoCollection.dataSource = self;
    _photoCollection.backgroundColor = [UIColor whiteColor];
    
    //注册item类型 这里使用系统的类型
    [_photoCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
    _photoButton = [[UIButton alloc] initWithFrame:CGRectMake(20, CGRectGetHeight(self.view.frame)-110, 80, 80)];
    [_photoButton addTarget:self action:@selector(goOnAction) forControlEvents:UIControlEventTouchUpInside];
    _photoButton.backgroundColor = [UIColor blackColor];
    _photoButton.alpha = 0.3;
    _photoButton.layer.cornerRadius = 40;
    _photoButton.layer.masksToBounds = YES;
    _photoLabel = [[UILabel alloc] initWithFrame:_photoButton.frame];
    _photoLabel.center = _photoButton.center;
    _photoLabel.text = @"+1";
    _photoLabel.textColor = [UIColor colorWithRGB:0x12d2c4];
    _photoLabel.font = [UIFont systemFontOfSize:18];
    _photoLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:_photoCollection];
    [self.view addSubview:_photoButton];
    [self.view addSubview:_photoLabel];
    
}

- (void)initViews
{
    BOOL naviHidden = [self navigationBarHidden];
    if (!naviHidden && self.navBar != nil)
    {
        [self.navBar setTitle:@""];
        [self.navBar customNaviLeftButton:self action:@selector(onBack:) title:@"取消"];
        [self.navBar customNaviRightButton:self action:@selector(onStore:) title:@"存储"];
    }
    
    _photoImageView = [[UIImageView alloc] initWithFrame:autoRectTableViewHaveBar(!naviHidden)];
    _photoImageView.contentMode = UIViewContentModeScaleAspectFill;
    [_photoImageView setUserInteractionEnabled:YES];
    _photoImageView.image = [[SDPhotoArray shareInstanse].photoImageArray objectAtIndex:0];
    _photoImageView.layer.masksToBounds = true;
    [self.view addSubview:_photoImageView];
    
    //注册item类型 这里使用系统的类型
    [_photoCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
    _photoButton = [[UIButton alloc] initWithFrame:CGRectMake(20, CGRectGetHeight(self.view.frame)-110, 80, 80)];
    [_photoButton addTarget:self action:@selector(goOnAction) forControlEvents:UIControlEventTouchUpInside];
    _photoButton.backgroundColor = [UIColor blackColor];
    _photoButton.alpha = 0.3;
    _photoButton.layer.cornerRadius = 40;
    _photoButton.layer.masksToBounds = YES;
    _photoLabel = [[UILabel alloc] initWithFrame:_photoButton.frame];
    _photoLabel.center = _photoButton.center;
    _photoLabel.text = @"+1";
    _photoLabel.textColor = [UIColor colorWithRGB:0x12d2c4];
    _photoLabel.font = [UIFont systemFontOfSize:18];
    _photoLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:_photoButton];
    [self.view addSubview:_photoLabel];
}

- (BOOL)navigationBarHidden
{
    return NO;
}

- (void)complete:(id)sender
{
    SelectViewAlert *alertView = [[SelectViewAlert alloc] init];
    [alertView setSelectArray:@[@"快速存储", @"保存为新患者", @"保存为现有患者"]];
    alertView.delegate = self;
    [alertView show];
}

- (void)onBack:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)setPhotoImage:(UIImage *)photoImage
{
    SDPhotoInfo* photoInfo = [[SDPhotoInfo alloc] init];
    photoInfo.creationTime = [[NSDate date] formattedString];
    photoInfo.updateTime = photoInfo.creationTime;
    photoInfo.id = arc4random() % 100000;
    
    [photoInfo copyTag:_comparePhotoInfo];
    
    [[SDPhotoArray shareInstanse] addPhotoInfo:photoInfo];
    [[SDPhotoArray shareInstanse] addPhtoImage:photoImage];
}

- (void)onStore:(id)sender
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        SDPhotoArray* photoArrayInstance = [SDPhotoArray shareInstanse];
        [photoArrayInstance.photoInfoArray enumerateObjectsUsingBlock:^(SDPhotoInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx < [photoArrayInstance.photoImageArray count]) {
                UIImage *photoImage = [photoArrayInstance.photoImageArray objectAtIndex:idx];
                [self saveOriginalImageToLocalFile:photoImage photoInfo:obj];
                [[SDPaientInfoMgr shareAGDatabaseManager] insert:obj tableName:kPhotoTableName];
                
            }
        }];
    }); 
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:NO completion:^{
            
            SDPhotoInfoViewController* photoInfoViewCtrl = [[SDPhotoInfoViewController alloc] init];
            photoInfoViewCtrl.photoInfoArray = [SDPhotoArray shareInstanse].photoInfoArray;
            SDNavigationController* navigationCtrl = [[SDNavigationController alloc] initWithRootViewController:photoInfoViewCtrl];
            
            SDTabBarController* tabBarController = [SDWindowManager defaultManager].getTabBarController;
            [tabBarController.selectedViewController presentViewController:navigationCtrl animated:YES completion:^(void){
            }];
            
        }];
        
    });
}

-(BOOL)saveResizedImageToLocalFile:(UIImage*)image photoInfo:(SDPhotoInfo*)photoInfo
{
    UIImage* resizeImg = [SDImage reSizeImage:image toSize:CGSizeMake(kMiddlePhotoWidth, kMiddlePhotoWidth)];
    
    NSString* identifier = [NSString randomAlphanumericStringWithLength:10];
    NSString* resizedFileName = [NSString stringWithFormat:@"%@.png",identifier];
    NSString* directory = [SDFile getDirectoryInCacheWithName:[NSString stringWithFormat:@"%@",kPhotoDiretoryName]];
    NSString *resizedFilePath = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",resizedFileName]];
    
    NSData *data = nil;
    
    data = UIImageJPEGRepresentation(resizeImg, 0.4);
    
    photoInfo.cropFileName = resizedFileName;
    
    return [[NSFileManager defaultManager] createFileAtPath:resizedFilePath contents:data attributes:nil];
}

-(BOOL)saveOriginalImageToLocalFile:(UIImage*)image photoInfo:(SDPhotoInfo*)photoInfo
{
    UIImage* originalImg =  image;
    
    NSString* identifier = [NSString randomAlphanumericStringWithLength:10];
    NSString* originalImgFileName = [NSString stringWithFormat:@"%@.jpg",identifier];
    NSString* directory = [SDFile getDirectoryInCacheWithName:[NSString stringWithFormat:@"%@",kPhotoDiretoryName]];
    NSString *originalImgFilePath = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",originalImgFileName]];
    
    NSData *data = UIImageJPEGRepresentation(originalImg, 0.4);
    photoInfo.originalFileName = originalImgFileName;
    return [[NSFileManager defaultManager] createFileAtPath:originalImgFilePath contents:data attributes:nil];
}

#pragma mark - uicontrol action
- (void)goOnAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UICollectionViewDataSource
//返回分区个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//返回每个分区的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [SDPhotoArray shareInstanse].photoInfoArray.count;
}
//返回每个item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    UIImageView *photoView = [[UIImageView alloc] initWithFrame:cell.bounds];
    photoView.contentMode = UIViewContentModeScaleAspectFill;
    [photoView setUserInteractionEnabled:YES];
    @try {
        photoView.image = [[SDPhotoArray shareInstanse].photoImageArray objectAtIndex:indexPath.row];
        photoView.layer.masksToBounds = true;
        [cell addSubview:photoView];
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(_photoViewWidth, _photoViewWidth);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1.0;
}

#pragma mark - SelectViewAlertDelegate
- (void)alertSelectAction:(SelectViewAlert*)view text:(NSString *)text index:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            [[SDPhotoArray shareInstanse].photoInfoArray enumerateObjectsUsingBlock:^(SDPhotoInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx < [[SDPhotoArray shareInstanse].photoImageArray count]) {
                    UIImage *photoImage = [[SDPhotoArray shareInstanse].photoImageArray objectAtIndex:idx];
                    [self saveOriginalImageToLocalFile:photoImage photoInfo:obj];
                    [[SDPaientInfoMgr shareAGDatabaseManager] insert:obj tableName:kPhotoTableName];
                }
                
            }];
            // 清除连拍缓存
            [[SDPhotoArray shareInstanse] removeAllPhoto];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 1:
        {
            SDPaientEditorViewController* editorViewController = [[SDPaientEditorViewController alloc] init];
            SDNavigationController* navigationCtrl = [[SDNavigationController alloc] initWithRootViewController:editorViewController];
            [self presentViewController:navigationCtrl animated:YES completion:nil];
            
            [editorViewController didSelectedItem:^(SDPaientInfoItem *item) {
                [[SDPhotoArray shareInstanse].photoInfoArray enumerateObjectsUsingBlock:^(SDPhotoInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (idx < [[SDPhotoArray shareInstanse].photoImageArray count])  {
                        UIImage *photoImage = [[SDPhotoArray shareInstanse].photoImageArray objectAtIndex:idx];
                        [self saveOriginalImageToLocalFile:photoImage photoInfo:obj];
                        obj.patientId = item.pId;
                        [[SDPaientInfoMgr shareAGDatabaseManager] insert:obj tableName:kPhotoTableName];
                        
                    }
                }];
                
                // 清除连拍缓存
                [[SDPhotoArray shareInstanse] removeAllPhoto];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self dismissViewControllerAnimated:YES completion:nil];
                });
            }];
        }
            break;
        case 2:
        {
            SDSelectPaientViewcontroller* selectPaientViewController = [[SDSelectPaientViewcontroller alloc] init];
            [self.navigationController pushViewController:selectPaientViewController animated:YES];
            
            [selectPaientViewController didSelectedItem:^(SDPaientInfoItem *item) {
                
                [[SDPhotoArray shareInstanse].photoInfoArray enumerateObjectsUsingBlock:^(SDPhotoInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (idx < [[SDPhotoArray shareInstanse].photoImageArray count])  {
                        UIImage *photoImage = [[SDPhotoArray shareInstanse].photoImageArray objectAtIndex:idx];
                        [self saveOriginalImageToLocalFile:photoImage photoInfo:obj];
                        obj.patientId = item.pId;
                        [[SDPaientInfoMgr shareAGDatabaseManager] insert:obj tableName:kPhotoTableName];
                    }
                    
                }];
                
                // 清除连拍缓存
                [[SDPhotoArray shareInstanse] removeAllPhoto];
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
        }
            break;
            
    }
}

@end
